package dao

import (
	"LibraryManagementSys/gorm/query"
	"LibraryManagementSys/pkg/config"
	"LibraryManagementSys/pkg/zaplogger"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var db *gorm.DB

// 根据配置文件中的参数, 拼接数据库连接字符串
func genConnectionUrl() string {
	cfg := config.Get().MySqlConfig
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.DatabaseName)
}

// New 初始化 MySQL 数据库连接
// @Description:
// @return error
func New() error {
	url := genConnectionUrl()
	fmt.Println("拼接的 sql 连接字符串:", url)

	var err error
	db, err = gorm.Open(mysql.Open(url), &gorm.Config{
		Logger:          zaplogger.NewGormLogger(zap.L()),
		CreateBatchSize: 500,
	})

	if err != nil {
		fmt.Println("数据库连接失败！")
		return err
	}

	// 设置 Gorm 自动生成链接的数据库
	query.SetDefault(db)

	return nil
}
